<template>
  <el-dialog
    class="public-dialog"
    :title="`${isEdit ? '修改' : '新增'}报关公司主体信息`"
    width="936"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div class="h-[460px]">
      <VForm
        ref="form"
        :model="model"
        :fieldList="fieldList"
        :options="formOption"
        :rules="rules"
        :disabled="disabled"
      >
        <template #seal_image="{ input, value }">
          <Upload
            label="电子印章"
            :modelValue="value"
            @update:modelValue="input"
            accept="image/png"
          >
            <template #headRight>
              <div class="text-[12px] text-[#999] leading-[17px]">
                <span class="mr-[2px] iconfont icon-hint_line"></span>
                <span>文件格式只能是PNG</span>
              </div>
            </template>
          </Upload>
        </template>
      </VForm>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus";
import VForm from "@/components/Form/index.vue";
import Upload from "@/components/Upload/index.vue";
import {
  declareCompanyAdd,
  declareCompanyUpdate,
  declareCompanyDetail,
} from "../api";

const props = defineProps({
  id: { type: [String, Number], default: "" },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
});

const emit = defineEmits(["update:modelValue", "refresh", "close"]);

const formOption = {
  inline: true,
  labelPosition: "top",
};

const rules = {
  seller_name: [{ required: true, message: "请输入卖方名称", trigger: "blur" }],
  buy_name: [{ required: true, message: "请输入买方名称", trigger: "blur" }],
};

const form = ref();
const model = ref({});
const loading = ref();

const publicStyle = { style: { minWidth: "240px" } };
const fieldList = [
  {
    field: "seller_name",
    label: "卖方名称",
    ...publicStyle,
  },
  {
    field: "seller_name_alias",
    label: "卖方名称简称",
    ...publicStyle,
  },
  {
    field: "seller_number",
    label: "卖方编号",
    ...publicStyle,
  },
  {
    field: "seller_linkman",
    label: "卖方联系人",
    ...publicStyle,
  },
  {
    field: "seller_tel",
    label: "卖方电话",
    ...publicStyle,
  },
  {
    field: "seller_fax",
    label: "卖方传真",
    ...publicStyle,
  },
  {
    field: "seller_address",
    label: "卖方地址",
    type: "textarea",
    autosize: { minRows: 4, maxRows: 8 },
    full: true,
    itemStyle: { width: "100%" },
  },
  {
    field: "buy_name",
    label: "买方名称",
    ...publicStyle,
  },
  {
    field: "buy_number",
    label: "买方编号",
    ...publicStyle,
  },
  {
    field: "buy_linkman",
    label: "买方联系人",
    ...publicStyle,
  },
  {
    field: "buy_tel",
    label: "买方电话",
    ...publicStyle,
  },
  {
    field: "buy_fax",
    label: "买方传真",
    ...publicStyle,
  },
  {
    field: "buy_address",
    label: "买方地址",
    type: "textarea",
    autosize: { minRows: 4, maxRows: 8 },
    full: true,
    itemStyle: { width: "100%" },
  },
  {
    field: "hs_code",
    label: "海关编码",
    ...publicStyle,
  },
  {
    field: "supply_goods",
    label: "供货源",
    ...publicStyle,
  },
  {
    field: "signing_place",
    label: "签约地点",
    type: "textarea",
    autosize: { minRows: 4, maxRows: 8 },
    full: true,
    itemStyle: { width: "100%" },
  },
  {
    field: "place_of_shipment",
    label: "发货地",
    type: "textarea",
    autosize: { minRows: 4, maxRows: 8 },
    full: true,
    itemStyle: { width: "100%" },
  },
  { type: "br" },
  { field: "seal_image", slot: "seal_image", style: { width: "100%" } },
];

watch(
  () => props.id,
  (val) => {
    if (val) {
      if (!props.modelValue) return;
      nextTick(() => {
        getDetail(val);
      });
    }
  }
);

const getDetail = async (id) => {
  try {
    const { data } = await declareCompanyDetail({ id });
    if (data?.seal_image && Object.keys(data?.seal_image)?.length) {
      data.seal_image = [
        {
          name: data.seal_image?.filename,
          url: data.seal_image?.oss_path,
          source_name: data.seal_image?.source_name,
        },
      ];
    } else {
      data.seal_image = [];
    }
    model.value = {
      ...data,
    };
  } catch (e) {
    model.value = {};
    console.error(e);
  }
};

const isEdit = computed(() => {
  return !!props.id;
});

const handleSave = async () => {
  try {
    const formInfo = await form.value.submit();
    const api = {
      edit: declareCompanyUpdate,
      add: declareCompanyAdd,
    };
    const { id } = props;
    formInfo.seal_image = formInfo?.seal_image?.[0]?.response || {};
    await api[isEdit.value ? "edit" : "add"]({
      id: id || undefined,
      ...formInfo,
    });
    ElMessage.success(isEdit.value ? "修改成功" : "保存成功");
    handleClose(true);
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
    console.error(e);
  } finally {
    loading.value = false;
  }
};

const handleClose = async (refresh) => {
  model.value = {};
  await nextTick();
  form.value.resetForm();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
